import WebGL = Laya.WebGL;
import Sprite = Laya.Sprite;
import Stage = Laya.Stage;
import Browser = Laya.Browser;
import Render = Laya.Render;
import Handler = Laya.Handler;

export default class WxSdk {
	constructor() { }

	/**
	  * 判断当前运行环境是否是微信
	  */
	public static isInWxDev(): boolean {
		let wx = WxSdk.getWx();
		return wx != null;
	}

	private static getWx(): any {
		let result: any = null;
		if (Browser.window && Browser.window.wx) {
			result = Browser.window.wx;
		}
		return result;
	}

	/**
	  * 初始化微信设置
	  * 包括分享，保持屏幕常亮，设置onShow,onHide
	  */
	// public static initWxSettings(): void {
	// 	this.wxUpdateShareMenu();
	// 	this.wxShowShareMenu();
	// 	this.wxSetKeepScreenOn();
	// 	this.wxOnShow();
	// 	this.wxSetOnHide();
	// }

	/**
	 * 监听微信onHide
	 * @param func 监听方法
	 */
	public static wxOnHide(func: Function): void {
		let wx = WxSdk.getWx();
		let emptyFunc = () => { };
		func = func || emptyFunc;
		wx && wx.onHide && wx.onHide(func);
	}

	/**
	 * 同步写入微信本地存储
	 * @param key key
	 * @param value value
	 */
	public static setStorageSync(key: string, value: any) {
		let wx = WxSdk.getWx();
		wx && wx.setStorageSync(key, value);
	}

	/**
	 * 同步读取微信本地存储
	 * @param key key
	 */
	public static getStorageSync(key: string) {
		let wx = WxSdk.getWx();
		return wx && wx.getStorageSync(key);
	}

	/**
	 * 保持屏幕常亮
	 * @param onSuccess 成功回调
	 * @param onFailed 失败回调
	 */
	public static wxSetKeepScreenOn(onSuccess: Function = null, onFailed: Function = null): void {
		let wx = WxSdk.getWx();
		let options = {
			keepScreenOn: true,
			success: (res) => {
				onSuccess && onSuccess(res);
			},
			fail: (err) => {
				onFailed && onFailed(err);
			}
		};
		wx && wx.setKeepScreenOn && wx.setKeepScreenOn(options);
	}

	/**
	 * 显示转发按钮
	 */
	public static wxShowShareMenu(): void {
		let wx = WxSdk.getWx();
		let options = {
			withShareTicket: true,
			success: () => { },
			fail: () => { }
		};

		wx && wx.showShareMenu && wx.showShareMenu(options);
	}


	/**
	 * 监听用户点击右上角菜单的“转发”按钮时触发的事件
	 * @param messageFunc 转发回调，需要返回一个{title: '', imageUrl: '', query: ''}格式的对象
	 */
	public static wxOnShareAppMessage(messageFunc: Function): void {
		let wx = WxSdk.getWx();
		wx && wx.onShareAppMessage && wx.onShareAppMessage(messageFunc);
	}

	/**
	 * 更新转发属性
	 */
	public static wxUpdateShareMenu(): void {
		let wx = WxSdk.getWx();
		wx && wx.updateShareMenu && wx.updateShareMenu({
			withShareTicket: true,
			success: () => { },
			fail: () => { }
		});
	}

	// wx登陆
	public static wxLogin(succHandler: Handler = null, failHandler: Handler = null): void {
		let lessRetryTime = 2;
		this.retryWxLogin(lessRetryTime, succHandler, failHandler);
	}

	public static retryWxLogin(lessRetryTime: number, succHandler: Handler = null, failHandler: Handler = null): void {
		let wx = WxSdk.getWx();
		let options = {
			success: (res) => {
				if (res.errMsg == "login:ok") {
					succHandler && succHandler.runWith(res);
				} else {
					failHandler && failHandler.runWith(res);
				}
			},
			fail: (err) => {
				if (lessRetryTime > 0) {
					this.retryWxLogin(lessRetryTime - 1, succHandler, failHandler);
				} else {
					failHandler && failHandler.runWith(err);
				}
			}
		};
		wx && wx.login && wx.login(options);
	}

	/**
	 * 跳转到微信客服
	 * @param succHandler 成功handler
	 * @param failHandler 失败handler
	 */
	public static wxCustomer(succHandler: Handler = null, failHandler: Handler = null): void {
		let wx = WxSdk.getWx();
		let options = {
			success: (res) => {
				succHandler && succHandler.runWith(res);
			},
			fail: (err) => {
				failHandler && failHandler.runWith(err);
			}
		};
		wx && wx.openCustomerServiceConversation && wx.openCustomerServiceConversation(options);
	}

	/**
	 * 微信http请求
	 * @param options 参考微信api文档
	 */
	public static wxRequest(options: any): void {
		let wx = WxSdk.getWx();
		wx && options && wx.request && wx.request(options);
	}


	/**
	 * 获取授权信息
	 * @param successHandler 
	 * @param failedHandler 
	 */
	public static wxGetAuthSettingSetting(successHandler: Handler = null, failedHandler: Handler = null): void {
		let wx = WxSdk.getWx();
		let options: any = {
			success: (res) => {
				if (res && res.authSetting) {
					successHandler && successHandler.runWith(res.authSetting);
				} else {
					failedHandler && failedHandler.run();
				}
			},
			fail: (err) => {
				failedHandler && failedHandler.runWith(err);
			}
		};

		wx && wx.getSetting && wx.getSetting(options);
	}

	/**
	 * 获取用户信息
	 * @param successHandler 
	 */
	public static wxGetUserInfo(successHandler: Handler = null): void {
		let wx = WxSdk.getWx();

		let options = {
			lang: "zh_CN",
			success: (res: any) => {
				successHandler && successHandler.runWith(res);
			},
			fail: (err) => {
			}
		};

		wx && wx.getUserInfo && wx.getUserInfo(options);
	}

	/**
	 * 退出小游戏
	 */
	public static wxExitMiniProgram(): void {
		let wx = WxSdk.getWx();
		wx && wx.exitMiniProgram && wx.exitMiniProgram();
	}

	/**
	 * 创建登陆按钮
	 * @param options 参考微信api
	 */
	public static wxCreateUserInfoButton(options): any {
		let res: any;
		let wx = WxSdk.getWx();

		if (wx && wx.createUserInfoButton) {
			res = wx.createUserInfoButton(options);
		}

		return res;
	}

	/**
	 * 获取微信登录参数
	 */
	public static wxGetLaunchOptions(): any {
		let wx = WxSdk.getWx();
		if (wx) {
			return wx.getLaunchOptionsSync();
		}
		return null;
	}

	/**
	 * 监听小游戏回到前台事件
	 * @param func 监听方法
	 */
	private static wxOnShow(func: Function): void {
		let wx = WxSdk.getWx();
		let emptyFunc = () => { };
		func = func || emptyFunc;
		wx && wx.onShow && wx.onShow(func);
	}

	/**
	 * 分享-> 拉起好友列表
	 * @param title:string 
	 * @param imgUrl:string
	 * @param query: string
	 **/
	public static wxShareAppMessage(title: string = "", imgUrl: string = "", query: string = ""): void {
		let wx: any = WxSdk.getWx();
		wx && wx.shareAppMessage && wx.shareAppMessage({
			title: title,
			imageUrl: imgUrl,
			query: query
		});
	}

	/**
	 * 跳转到小程序
	 * @param shareUrl 目标小程序url
	 */
	public static navigate2MiniProgram(appId: string, path: string = '', successHandler: Handler = null, failedHandler: Handler = null): void {
		let wx = WxSdk.getWx();
		let options = {
			appId: appId,
			path: path,
			success: (res) => {
				successHandler && successHandler.runWith(res);
			},
			fail: (err) => {
				failedHandler && failedHandler.runWith(err);
			}
		};
		wx && wx.navigateToMiniProgram && wx.navigateToMiniProgram(options);
	}

	// 获取开放数据域
	private static openDataContext: any;
	public static getOpenDataContext(): void {
		let wx = WxSdk.getWx();
		wx && wx.getOpenDataContext && (WxSdk.openDataContext = wx.getOpenDataContext());
	}

	/**
	 * 与子域通信
	 * @param msg 通信内容
	 */
	public static wxPostMessage(msg: any): void {
		WxSdk.getOpenDataContext();
		if (WxSdk.openDataContext == null) {
			return;
		}
		WxSdk.openDataContext.postMessage(msg);
	}

	// TODO: 整理广告部分api
	// 显示banner广告
	private static _bannerAd: any = null;
	public static wxCreateBannerAd(): void {
		let wx = WxSdk.getWx();

		if (WxSdk._bannerAd != null) {
			WxSdk._bannerAd.show();
		} else {
			let top: number = 0;
			let left: number = Browser.clientWidth / 2 - 175;
			if ((Browser.clientWidth == 375 && Browser.clientHeight == 812 && Browser.pixelRatio == 3) || (Browser.clientWidth == 360 && Browser.clientHeight == 760 && Browser.pixelRatio == 3)) {
				top = 44;
			}
			if (wx) {
				let obj: any = {
					adUnitId: 'adunit-fe783a13acba642f',
					style: {
						left: left,
						top: top,
						width: 350
					}

				};
				WxSdk._bannerAd = wx.createBannerAd(obj);
				WxSdk._bannerAd.show();
			}
		}
	}

	public static wxUnShowBannerAd(): void {
		if (WxSdk._bannerAd) {
			WxSdk._bannerAd.hide();
		}
	}

	// 广告视频
	public static wxCreateRewardVideoAd(successHandler: Handler): void {
		let wx = WxSdk.getWx();

		if (!wx) {
			return;
		}

		let videoAd: any;
		wx.createRewardedVideoAd && (videoAd = wx.createRewardedVideoAd({ adUnitId: 'adunit-dc1ccc1677712594' }));

		if (videoAd) {
			let closeFunc: Function = (res) => {
				if (res && res.isEnded || res === undefined) {
					// 正常播放结束，可以下发游戏奖励
					successHandler && successHandler.run();
					console.log("videoAd end");
				}
				else {
					// 播放中途退出，不下发游戏奖励
					console.log("videoAd abort ");
				}
			};

			videoAd.load().then(function (): void {
				videoAd.show();
			});

			videoAd.onClose(closeFunc);
		}
	}

	/**
	 * 同步获取设备信息
	 */
	public static wxGetSystemInfoSync() {
		let wx = WxSdk.getWx();
		return wx ? wx.getSystemInfoSync() : null;
	}

    /**
     * 使手机发生较长时间的振动（400 ms)
     * @param obj： Object 
     *         success    function        非必须    接口调用成功的回调函数
     *            fail    function        非必须    接口调用失败的回调函数    
     *         complete   function        非必须    接口调用结束的回调函数（调用成功、失败都会执行）    
     */
	public static vibrateLong(obj: Object) {
		let wx = WxSdk.getWx();
		if (wx) {
			wx.vibrateLong(obj);
		}
	}

    /**
     * 使手机发生较短时间的振动（15 ms）。仅在 iPhone 7 / 7 Plus 以上及 Android 机型生效
     * @param obj： Object 
     *         success    function        非必须    接口调用成功的回调函数
     *            fail    function        非必须    接口调用失败的回调函数    
     *         complete   function        非必须    接口调用结束的回调函数（调用成功、失败都会执行）    
     */
	public static vibrateShort(obj: Object) {
		let wx = WxSdk.getWx();
		if (wx) {
			wx.vibrateShort(obj);
		}
	}
}

